import 'whatwg-fetch';
import { message } from 'antd';

class Ajax {
  public post(url: string, params?: Object): Promise<any> {
    return fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'token': localStorage.getItem('token')
      },
      body: JSON.stringify(params)
    }).then(this.checkStatus).then(this.parseJSON).then((data: any) => {
      if (data.code === '0001') {
        localStorage.clear();
        sessionStorage.clear();
        location.replace('/');
        return;
      }
      return data;
    }).catch((err) => {
      message.error('请求失败，请稍后重试！');
      throw err;
    });
  }

  private isSuccess = (res: Response): boolean => res.status > 200 && res.status < 300;

  private checkStatus = (res: Response) => this.isSuccess ? res : this.handleError(res);

  private parseJSON = (res: Response) => res.json();

  private parseBlob = (res: Response) => res.blob();

  private handleError = (res: Response) => {
    let error: any = new Error(res.statusText);
    error.response = res;
    throw error;
  }
}

export default new Ajax;